package com.itwk.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.itwk.common.constant.ProductSearchConstant;
import com.itwk.common.to.search.SearchModel;
import com.itwk.gulimall.search.config.ElasticsearchConfig;
import com.itwk.gulimall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: wangke
 * @Date: 2021/01/26/下午 4:58
 * @Description:
 */
@Service
@Slf4j
public class SearchServiceImpl implements SearchService {
    @Autowired
   private  RestHighLevelClient restHighLevelClient ;  //注入es客户端
    @Override  //将数据 批量保存到es
    public boolean saveBulk(List<SearchModel> searchModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest(); //创建批量保存 请求
        //将数据封装到单个保存请求，再封装到批量保存请求中
        for (SearchModel searchModel : searchModels) {
            IndexRequest indexRequest = new IndexRequest(ProductSearchConstant.UP_INDEX).id(searchModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(searchModel);
            indexRequest.source(jsonString,XContentType.JSON);
            bulkRequest.add(indexRequest);

        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();   //获取到保存状态信息
        BulkItemResponse[] items = bulk.getItems(); //获取到存储元素
        List<String> ids =new ArrayList<>();
        for (BulkItemResponse item : items) {   //遍历保存保存出错的元素
            if( item.isFailed()){
                ids.add(item.getId());
            }
        }
        if(b){
            log.error("上架数据出错{}"+ids.toString());

        }else{
            log.info("上架数据成功。。。");
        }

        return !b;
    }
}
